import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'model.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';

class EditPersonage extends StatelessWidget {
  final UserObj userObj;
  //初始化函数
  EditPersonage({Key key, @required this.userObj}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text('个人信息'),
        centerTitle: true,
        elevation: 0.0,
      ),
      body: Theme(
        data: Theme.of(context).copyWith(
          primaryColor: Colors.black,
        ),
        child: Container(
            padding: EdgeInsets.all(16.0),
            child: KeyboardAvoider(
              autoScroll: true,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  EditPersonageForm(userObj: this.userObj),
                ],
              ),
            )),
      ),
    );
  }
}

class EditPersonageForm extends StatefulWidget {
  final UserObj userObj;
  //初始化函数
  EditPersonageForm({Key key, @required this.userObj}) : super(key: key);
  @override
  EditPersonageFormState createState() =>
      EditPersonageFormState(userObj: this.userObj);
}

class EditPersonageFormState extends State<EditPersonageForm> {
  UserObj userObj;
  //初始化函数
  EditPersonageFormState({Key key, @required this.userObj});
  final editPersonageFormKey = GlobalKey<FormState>();
  bool autovalidate = false;
  String uniqueId = '';
  SharedPreferences prefs;
  String nickname, email;

  @override
  void initState() {
    super.initState();
    nickname = userObj.nickname;
    email = userObj.email;
  }

  void submitEditPersonageForm() {
    if (editPersonageFormKey.currentState.validate()) {
      editPersonageFormKey.currentState.save();
      this.fetchPosts(nickname, email);
      EasyLoading.show(
          status: 'loading...', maskType: EasyLoadingMaskType.black);
    } else {
      setState(() {
        autovalidate = true;
      });
    }
  }

  String validateNickname(value) {
    if (value.isEmpty) {
      return '昵称不能为空！';
    }
    return null;
  }

  String validateEmail(value) {
    if (value.isEmpty) {
      return '邮箱不能为空！';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: editPersonageFormKey,
      child: Column(
        children: <Widget>[
          TextFormField(
            initialValue: nickname,
            decoration: InputDecoration(
              labelText: '昵称',
              helperText: '',
            ),
            onSaved: (value) {
              nickname = value;
            },
            validator: validateNickname,
            // autovalidate: autovalidate,
          ),
          TextFormField(
            keyboardType: TextInputType.emailAddress, //电子邮箱类型的输入
            initialValue: email,
            decoration: InputDecoration(
              labelText: '邮箱',
              helperText: '',
            ),
            onSaved: (value) {
              email = value;
            },
            validator: validateEmail,
            // autovalidate: autovalidate,
          ),
          SizedBox(
            height: 32.0,
          ),
          Container(
            width: double.infinity,
            child: ElevatedButton(
              // color: Theme.of(context).accentColor,
              child: Text('保存', style: TextStyle(color: Colors.white)),
              onPressed: submitEditPersonageForm,
            ),
          ),
        ],
      ),
    );
  }

  Future fetchPosts($nickname, $email) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var dataBody = jsonEncode({'nickname': $nickname, 'email': $email});
    final response = await http.post(
        'https://me.yuanqiao.pw/api/me/edit-personage.php',
        body: dataBody,
        headers: {HttpHeaders.authorizationHeader: prefs.get('user_token')});
    EasyLoading.dismiss();
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      var state = responseBody['state'];
      if (state == '1') {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('nickname', responseBody['data']['nickname']);
        prefs.setString(
            'email',
            responseBody['data']['email'] != null
                ? responseBody['data']['email']
                : '');
        Fluttertoast.showToast(
            msg: responseBody['error'],
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black87,
            fontSize: 16.0);
        // Navigator.pop(context, '传递返回的数据');
        Navigator.pop(context);
      } else {
        Fluttertoast.showToast(
            msg: responseBody['error'],
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black87,
            fontSize: 16.0);
      }
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }
}
